package com.danger.Activity;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.danger.Listener.OnScanListener;
import com.danger.Model.adapter.ImageAdapter;
import com.danger.Model.bean.FolderBean;
import com.danger.Widget.ListImageDirPopupWindow;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


    private GridView gridView;
    private ImageAdapter adapter;
    private TextView dir_name_textView;
    private TextView count_textView;
    private RelativeLayout bottom_layout;
    private ProgressDialog dialog;

    private List<String> images;
    private File currentDir;
    private int maxCount;

    private List<FolderBean> folderBeans = new ArrayList<>();

    private ListImageDirPopupWindow mDirPopupWindow;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initDatas(new OnScanListener() {
            @Override
            public void onSuccess(File file, List<FolderBean> list) {
                currentDir = file;
                folderBeans = list;
                dialog.dismiss();
                data2View();
                initDirPopWindow();
            }

            @Override
            public void onError(String message) {

            }
        });
        initEvent();
    }

    private void initDirPopWindow() {
        mDirPopupWindow = new ListImageDirPopupWindow(this, folderBeans);
        mDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();
            }
        });

        mDirPopupWindow.setOnDirSelectedListener(new ListImageDirPopupWindow.OnDirSelectedListener() {
            @Override
            public void onSelected(FolderBean folderBean) {
                images = new ArrayList<>();
                Log.i("TAG", folderBean.getFirstImgPath());
                currentDir = new File(folderBean.getDir());
                File[] list = currentDir.listFiles();
                Log.i("TAG", "list ---->>" + list[0].getName());
                for (int i = 0; i < list.length; i++) {
                    if (list[i].getName().endsWith(".jpg") || list[i].getName().endsWith(".jpeg") || list[i].getName().endsWith(".jpeg")) {
                        images.add(list[i].getAbsolutePath());
                    }
                }
                Log.i("TAG", "image1" + images.get(0).toString());

                adapter = new ImageAdapter(MainActivity.this, images);
                gridView.setAdapter(adapter);
                count_textView.setText(images.size() + "张");
                dir_name_textView.setText(folderBean.getName());
                mDirPopupWindow.dismiss();
            }
        });
    }


    /**
     * 将内容区域变量
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    /**
     * 将内容区域变暗
     */
    private void lightOff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
    }

    private void initView() {
        gridView = (GridView) findViewById(R.id.gridView);
        bottom_layout = (RelativeLayout) findViewById(R.id.bottom_layout);
        dir_name_textView = (TextView) findViewById(R.id.dir_name_textView);
        count_textView = (TextView) findViewById(R.id.count_textView);
    }

    /**
     * 利用ContentProvider扫面手机中的所有图片
     */
    private void initDatas(final OnScanListener listener) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "当前存储卡不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        dialog = ProgressDialog.show(this, null, "正在加载...");
        new Thread() {
            @Override
            public void run() {
                Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = MainActivity.this.getContentResolver();
                Cursor cursor = cr.query(uri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);

                Set<String> mDirPaths = new HashSet<String>();

                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();

                    FolderBean folderBean = null;


                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        folderBean = new FolderBean();
                        folderBean.setDir(dirPath);
                        folderBean.setFirstImgPath(path);
                    }

                    if (parentFile.list() == null)
                        continue;
                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                                return true;
                            }

                            return false;
                        }
                    }).length;

                    folderBean.setCount(picSize);

                    folderBeans.add(folderBean);

                    if (picSize > maxCount) {
                        maxCount = picSize;
                        currentDir = parentFile;
                    }
                    listener.onSuccess(parentFile, folderBeans);
                }
                cursor.close();
            }
        }.start();
    }

    private void initEvent() {
        bottom_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDirPopupWindow.setAnimationStyle(R.style.die_popupwindow_anim);
                mDirPopupWindow.showAsDropDown(bottom_layout, 0, 0);
                lightOff();
            }
        });
    }


    /**
     * 绑定数据到View中
     */
    private void data2View() {
        if (currentDir == null) {
            Toast.makeText(this, "未扫描到任何图片", Toast.LENGTH_SHORT).show();
            return;
        }
//        images = Arrays.asList(currentDir.list());
        images = new ArrayList<>();
        File[] list = currentDir.listFiles();
        Log.i("TAG", "list ---->>" + list[0].getName());
        for (int i = 0; i < list.length; i++) {
            if (list[i].getName().endsWith(".jpg") || list[i].getName().endsWith(".jpeg") || list[i].getName().endsWith(".jpeg")) {
                Log.i("TAG", "first getAbsolutePath--------->>>" + list[i].getAbsolutePath());
                images.add(list[i].getAbsolutePath());
            }
        }

        adapter = new ImageAdapter(this, images);
        handler.post(new Runnable() {
            @Override
            public void run() {
                gridView.setAdapter(adapter);
                count_textView.setText(maxCount + "");
                dir_name_textView.setText(currentDir.getName());
            }
        });
    }
}